package com.sxkf.template.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sxkf.core.common.wx.WxLoginUtil;
import com.sxkf.core.constant.Constants;
import com.sxkf.core.third.im.entity.AddFriend;
import com.sxkf.core.third.im.entity.ExtensionJsonEntity;
import com.sxkf.core.third.im.entity.UpdateUser;
import com.sxkf.core.third.im.service.YxService;
import com.sxkf.template.entity.SysConfig;
import com.sxkf.template.entity.UserLike;
import com.sxkf.template.service.SysConfigService;
import com.sxkf.template.service.UserLikeService;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.SxkfException;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RedisUtils;
import com.sxkf.template.entity.User;
import com.sxkf.template.service.LoginService;
import com.sxkf.template.service.UserService;
import com.sxkf.template.vo.request.user.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.SecureRandom;
import java.util.UUID;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private UserService userService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private YxService yxService;
    @Resource
    private UserLikeService userLikeService;
    @Resource
    private SysConfigService sysConfigService;
    

    private static final String CAPTCHA_PREFIX = "CAPTCHA:";
    private static final String CAPTCHA_FORGET = "CAPTCHA_FORGET:";

    @Override
    public UserLoginVo wxLogin(String openCode, String phoneCode) {
        log.info("openCode:{},phoneCode:{}", openCode, phoneCode);

        if (StringUtils.isEmpty(openCode) || StringUtils.isEmpty(phoneCode)) {
            throw new SxkfException("code值为空");
        }

        String userOpenid = WxLoginUtil.returnOpenid(openCode);
        log.info("openid:{}", userOpenid);
        String phone = WxLoginUtil.returnTel(phoneCode);
        log.info("phone:{}", phone);

        if (StringUtils.isEmpty(userOpenid)) {
            throw new SxkfException("后端获取openid失败");
        }

        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getOpenId,userOpenid));
        user.setIsOnline("1");
        //若不存在该用户则进行注册
        if (user == null) {
            user = createUser(userOpenid, phone, null);
        }

        //构造登录VO返回给前端
        return getUserLoginVo(user);
    }

    @NotNull
    private UserLoginVo getUserLoginVo(User user) {
        String token = JwtUtil.sign("user::"+user.getId(), user.getPhone());
        UserLoginVo userLoginVo = new UserLoginVo();
        userLoginVo.setToken(token);
        userLoginVo.setUserId(user.getId());
        userLoginVo.setImToken(user.getImToken());
        redisUtils.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtils.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 24 * 7);
        return userLoginVo;
    }

    @Override
    public UserLoginVo telLogin(String phoneNumber, String captcha) {
//        String captchaCode = redisUtil.get(CAPTCHA_PREFIX + phoneNumber);
//        if (null == captchaCode){
//            throw new SxkfException("验证码已过期");
//        }
//        if (!captchaCode.equals(captcha)){
//            throw new SxkfException("验证码输入错误");
//        }

        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, phoneNumber));
        if (user == null){
            throw new SxkfException("手机号未注册");
        }
        return getUserLoginVo(user);
    }

    @Override
    public UserLoginVo pwdLogin(String phoneNumber, String password) {
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, phoneNumber));
        if (user == null){
            throw new SxkfException("手机号未注册");
        }
        if (!user.getPassword().equals(password)){
            throw new SxkfException("账号或密码错误");
        }
        return getUserLoginVo(user);
    }

    @NotNull
    private User createUser(String openId, String phone, String password) {
        User user = new User();
        user.setIsDeleted("0");
        user.setOpenId(openId);
        user.setPassword(password);
        user.setPhone(phone);
        //默认昵称
        user.setNickName(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 6));
        //默认头像
        user.setAvatar(Constants.USER_AVATAR);
        userService.save(user);
        String imToken = yxService.register(user.getId());
        user.setImToken(imToken);
        userService.updateById(user);
        return user;
    }

    @Override
    public void sendCaptcha(String phoneNumber) {
        String code = creatCode();
        //todo 接入短信

        redisUtils.set(CAPTCHA_PREFIX+phoneNumber,code,120);
        System.out.println(phoneNumber+"的验证码为:"+code);
    }

    @Override
    public UserLoginVo register(User user) {
        SysConfig kefuId = sysConfigService.getOne(new LambdaQueryWrapper<SysConfig>()
                .eq(SysConfig::getConfigKey, "kefu_id"));
        //        String captchaCode = redisUtil.get(CAPTCHA_PREFIX + phoneNumber);
//        if (null == captchaCode){
//            throw new SxkfException("验证码已过期");
//        }
//        if (!captchaCode.equals(captcha)){
//            throw new SxkfException("验证码输入错误");
//        }
        long count = userService.count(new LambdaQueryWrapper<User>().eq(User::getPhone, user.getPhone()));
        if (count>0){
            throw new SxkfException("该手机号已注册");
        }
        User realUser = createUser(null, user.getPhone(), user.getPassword());
        UpdateUser updateUser = new UpdateUser();
        updateUser.setAvatar(realUser.getAvatar());
        updateUser.setName(realUser.getNickName());
        ExtensionJsonEntity extensionJsonEntity = new ExtensionJsonEntity();
        extensionJsonEntity.setType("1");
        String extension = JSONUtil.toJsonStr(extensionJsonEntity);
        updateUser.setExtension(extension);
        yxService.updateUser(realUser.getId(), updateUser);
        // 加官方客服为好友
        AddFriend addFriend = new AddFriend();
        addFriend.setAccount_id(realUser.getId());
        addFriend.setFriend_account_id(kefuId.getConfigValue());
        yxService.addFriend(1,addFriend);
        // 加好友关系
        UserLike userLike = new UserLike();
        userLike.setUserId(realUser.getId());
        userLike.setLikeUserId(kefuId.getConfigValue());
        userLikeService.add(userLike);
        userLike.setId(null);
        userLike.setLikeUserId(realUser.getId());
        userLike.setUserId(kefuId.getConfigValue());
        userLikeService.add(userLike);

//        User user1 = userService.getOne(new LambdaQueryWrapper<User>()
//                .eq(User::getPhone, user.getPhone())
//                .eq(User::getPassword, user.getPassword())
//        );

        return getUserLoginVo(realUser);
    }

    @Override
    public String logout(HttpServletRequest request) {

        //用户退出逻辑
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);

        redisUtils.del(CommonConstant.PREFIX_USER_TOKEN + token);


        return "已成功登出";
    }

    @Override
    public Boolean forgetPass(String phoneNumber, String captcha, String newPass) {
//        String captchaCode = redisUtil.get(CAPTCHA_FORGET + phoneNumber);
//        if (null == captchaCode){
//            throw new SxkfException("验证码已过期");
//        }
//        if (!captchaCode.equals(captcha)){
//            throw new SxkfException("验证码输入错误");
//        }


        boolean update = userService.update(new LambdaUpdateWrapper<User>()
                .set(User::getPassword, newPass)
                .eq(User::getPhone, phoneNumber));

        return update;
    }

    @Override
    public void sendForgetCaptcha(String phoneNumber) {
        String code = creatCode();
        //todo 接入短信

        redisUtils.set(CAPTCHA_FORGET+phoneNumber,code,120);
        System.out.println(phoneNumber+"的验证码为:"+code);
    }

    private String creatCode() {
        SecureRandom random = new SecureRandom();
        int i = random.nextInt(899999) + 100000;
        return i + "";
    }
}
